package com.whitedust.top60;

/**
 *
 * @author A
 * @since 2025/11/10 16:36
 */

public class Top54 {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        // 保存计算结果
        String res = "0";

        int m = num1.length();
        int n = num2.length();
        for (int i = n - 1; i >= 0; i--) {
            int carry = 0;
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < n - i - 1; j++) {
                sb.append('0');
            }
            int n2 = num2.charAt(i) - '0';
            for (int j = m - 1; j >= 0 || carry != 0; j--) {
                int n1 = j < 0 ? 0 : num1.charAt(j) - '0';
                int product = n2 * n1 + carry;
                sb.append(product % 10);
                carry = product / 10;
            }
            res = add(res, sb.reverse().toString());
        }
        return res;
    }

    private String add(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int add = 0;
        for (int i = num1.length() - 1, j = num2.length() - 1;
             i >= 0 || j >= 0 || add != 0;
             i--, j--) {
            int x = i < 0 ? 0 : num1.charAt(i) - '0';
            int y = j < 0 ? 0 : num2.charAt(j) - '0';
            int sum = x + y + add;
            sb.append(sum % 10);
            add = sum / 10;
        }
        return sb.reverse().toString();
    }
}
